<?php
/**
*  文章控制器
*/
namespace app\admin\controller;
use app\admin\model\Index as IndexModel;
use app\admin\model\Content as ContentModel;
use app\admin\model\Company as CompanyModel;
use app\admin\model\Site as SiteModel;
use app\admin\model\ContentSort as ContentSortModel;
use app\admin\model\ModelM as ModelMModel;
use app\admin\model\Extfieldm as ExtfieldModel;
class Content extends Common
{
    private $model;
	private $commodel;
	private $sitemodel;
    private $blank;
	private $PageCount=20;
	private $SortModel;
	private $modelExt;
	public function _initialize()
    {
		parent::_initialize();
        $this->model = new ContentModel();
		$this->commodel = new CompanyModel();
		$this->modelExt = new ExtfieldModel();
		$this->sitemodel = new SiteModel();
		$this->assign('companys', $this->commodel->getList());
		$this->assign('sites', $this->sitemodel->getList());
    }
    //文章列表
    public function index()
    {
		$UrlParam=input();
		if(!isset($UrlParam['lkid']) || empty($UrlParam['lkid'])){
			$UrlParam['lkid']=0;
		}
        if ((! ! $id = input('id')) && $result = $this->model->getContent($id)) {
            $this->assign('more', true);
            $this->assign('content', $result);
        } else {

            if (! $mcode = input('mcode')) {
                $this->error('传递的模型编码参数有误，请核对后重试！');
            }
            if (isset($UrlParam['keyword'])) {
                if (! ! $scode = input('scode')) {
					$UrlParam1['keyword']=trim(input('keyword'));
					$UrlParam1['scode']=intval(input('scode'));
					$UrlParam1['mcode']=intval($mcode);
					$UrlParam1['lkid']=$UrlParam['lkid'];

                    $result = $this->model->findContent($UrlParam1,$this->PageCount);
                } else {
					$UrlParam2['keyword']=trim(input('keyword'));
					$UrlParam2['mcode']=intval($mcode);
					$UrlParam2['lkid']=$UrlParam['lkid'];
                    $result = $this->model->findContentAll($UrlParam2,$this->PageCount);
					//echo $this->model->getlastsql();
					//die;
                }
            } else {
				//unset($UrlParam['keyword']);
				//unset($UrlParam['scode']);
                $result = $this->model->getList($UrlParam,$this->PageCount);
				//echo $this->model->getlastsql();
				//die;
            }
            $this->assign('contents', $result);
			$this->assign('UrlParam', $UrlParam);
            // 文章分类下拉列表
			$this->SortModel = new ContentSortModel();
            $sort_select = $this->SortModel->getListSelect($mcode);

			$search_select=$this->makeSortSelect($sort_select,input('scode'));

            $this->assign('search_select', $search_select);

            $this->assign('sort_select', $this->makeSortSelect($sort_select, session('addscode')));

            $this->assign('subsort_select', $this->makeSortSelect($sort_select));
            // 模型名称
			$ModelM=new ModelMModel();
            $this->assign('model_name', $ModelM->getName($mcode));
        }
		$this->assign('extfield', $this->modelExt->getModelField($mcode));
		return $this->fetch("content");
    }

    // 文章增加
    public function add()
    {
		$UrlParam=input();
		if($this->request->isPost()){
			if (session('formcheck')!= input('formcheck/s')) {
				alert('表单提交校验失败,请刷新后重试！','back');
			}
            // 获取数据
            $scode = $UrlParam['scode'];
            $subscode = isset($UrlParam['subscode'])?$UrlParam['subscode']:'';
			$rund1 = isset($UrlParam['rund1'])?$UrlParam['rund1']:0;
			$rund2 = isset($UrlParam['rund2'])?$UrlParam['rund2']:0;
			$rund3 = isset($UrlParam['rund3'])?$UrlParam['rund3']:0;
			$lkid = $UrlParam['lkid'];
            $title = $UrlParam['title'];
            $titlecolor = $UrlParam['titlecolor'];
            $subtitle = $UrlParam['subtitle'];
            $filename = $UrlParam['filename'];
            $author = $UrlParam['author'];
            $source = $UrlParam['source'];
            $outlink = $UrlParam['outlink'];
            $date = $UrlParam['date'];
            $ico = !empty($UrlParam['ico'])?$UrlParam['ico']:'';
            $pics = !empty($UrlParam['pics'])?$UrlParam['pics']:'';
			if (!input('content')) {
                alert('内容不能为空！','back');
            }
            $content = $UrlParam['content'];
            $tags = str_replace('，', ',', $UrlParam['tags']);
            $enclosure = $UrlParam['enclosure'];
            $keywords = $UrlParam['keywords'];
            $description = $UrlParam['description'];
            $status = intval($UrlParam['status']);
            $istop = !empty($UrlParam['istop'])?$UrlParam['istop']:0;
            $isrecommend = !empty($UrlParam['isrecommend'])?$UrlParam['isrecommend']:0;
            $isheadline = !empty($UrlParam['isheadline'])?$UrlParam['isheadline']:0;
			$isslide = !empty($UrlParam['isslide'])?$UrlParam['isslide']:0;
            if (! $scode) {
                alert('内容分类不能为空！','back');
            }

            if (! $title) {
                alert('文章标题不能为空！','back');
            }

            if ($filename && ! preg_match('/^[a-zA-Z0-9\-]+$/', $filename)) {
                alert('内容URL名称只允许字母、数字、横线组成!','back');
            }
            // 自动提起前一百个字符为描述
            if (! $description && isset($UrlParam['content'])) {
                $description = escape_string(clear_html_blank(substr_both(strip_tags($UrlParam['content']), 0, 150)));
            }
            // 记住新增栏目
            session('addscode', $scode);

            // 构建数据
            $data = array(
                'acode' => 'cn',
                'scode' => $scode,
				'lkid' => $lkid,
				'rund3' => $rund3,
				'rund1' => $rund1,
				'rund2' => $rund2,
                'subscode' => $subscode,
                'title' => $title,
                'titlecolor' => $titlecolor,
                'subtitle' => $subtitle,
                'filename' => $filename,
                'author' => $author,
                'source' => $source,
                'outlink' => $outlink,
                'date' => $date,
                'ico' => $ico,
                'pics' => $pics,
                'content' => $content,
                'tags' => $tags,
                'enclosure' => $enclosure,
                'keywords' => $keywords,
                'description' => clear_html_blank($description),
                'sorting' => 255,
                'status' => $status,
                'istop' => $istop,
                'isrecommend' => $isrecommend,
                'isheadline' => $isheadline,
				'isslide' => $isslide,
                'visits' => 0,
                'likes' => 0,
                'oppose' => 0,
				'create_time' => date('Y-m-d H:i:s',time()),
				'update_time' => date('Y-m-d H:i:s',time()),
                'create_user' => session('username'),
                'update_user' => session('username')
            );

			//echo $this->model->getlastsql();
            // 执行添加
            if (! ! $id = $this->model->addContent($data)) {
				 foreach ($UrlParam as $key => $value) {
                    if (preg_match('/^ext_[\w\-]+$/', $key)) {
                        if (! isset($data2['contentid'])) {
                            $data2['contentid'] = $id;
                        }
                         $temp = $UrlParam[$key];
                        if (is_array($temp)) {
                            $data2[$key] = implode(',', $temp);
                        } else {
                            $data2[$key] = str_replace("\r\n", '<br>', $temp);
                        }
                    }
                }
                if (isset($data2)) {
                    if (! $this->model->addContentExt($data2)) {
                        $this->model->delContent($id);
                        $this->error('新增失败！', - 1);
                    }
                }
               $this->success('新增成功！', url('/Content/index/mcode/' . $UrlParam['mcode']));
            } else {
                 $this->error('新增失败！', - 1);
            }
        } else {
            $this->assign('add', true);
            if (! $mcode = $UrlParam['mcode']) {
                 $this->error('传递的模型编码参数有误，请核对后重试！');
            }
            // 文章分类
			$sort_model = new ContentSortModel();
            $sort_select = $sort_model->getListSelect($mcode);
            $this->assign('sort_select', $this->makeSortSelect($sort_select, session('addscode')));
            $this->assign('subsort_select', $this->makeSortSelect($sort_select));
			$this->assign('scode',$UrlParam['mcode']);
			 // 模型名称
			$ModelM=new ModelMModel();
            $this->assign('model_name', $ModelM->getName($mcode));
            // 扩展字段
			$WholeType=getwholelist(0,$mcode);
			$this->assign('WholeType', $WholeType);
			$ExtfieldModel=new ExtfieldModel();
            $this->assign('extfield', $ExtfieldModel->getModelField($mcode));
            return $this->fetch("content");
        }
    }
    // 生成分类选择
    private function makeSortSelect($tree, $selectid = null)
    {
        $list_html = '';
        foreach ($tree as $value) {
            // 默认选择项
            if ($selectid == $value->scode) {
                $select = "selected='selected'";
            } else {
                $select = '';
            }
            $list_html .= "<option value=".$value->scode." ".$select.">".$this->blank.$value->name."";
            // 子菜单处理
            if ($value->son) {
                $this->blank .= '　　';
                $list_html .= $this->makeSortSelect($value->son, $selectid);
            }
        }
        // 循环完后回归位置
        $this->blank = substr($this->blank, 0, - 6);
        return $list_html;
    }
    // 文章删除
    public function del()
    {
		$UrlParam=input();
		if($this->request->isPost()){
        // 执行批量删除
		$list = $UrlParam['list'];
            if ($list) {
                if ($this->model->delContentList($list)) {
                    $this->model->delContentExtList($list);
                    $this->success('批量删除成功！');
                } else {
                    $this->error('批量删除失败！');
                }
            } else {
                alert('请选择要删除的内容！','back');
            }
        }

        if (! $id = intval($UrlParam['id'])) {
            $this->error('传递的参数值错误！');
        }

        if ($this->model->delContent($id)) {
            $this->model->delContentExt($id);
            $this->success('删除成功！');
        } else {
            $this->error('删除失败！');
        }
    }
    // 文章修改
    public function mod()
    {
		
		$UrlParam=input();
		

		$submit = trim(input('submit'));
        if ($submit) {
            switch ($submit) {
                case 'sorting': //修改列表排序
                    $listall = $UrlParam['listall'];
                    if ($listall) {
                        $sorting = $UrlParam['sorting'];
                        foreach ($listall as $key => $value) {
                            if ($sorting[$key] === '' || ! is_numeric($sorting[$key]))
                                $sorting[$key] = 255;
                            $this->model->modContent($value, "sorting=" . $sorting[$key]);
                        }
                        $this->success('修改成功！');
                    } else {
                        alert('排序失败，无任何内容！','back');
                    }
                    break;
                case 'copy':
                    $list = input('list/a');
                    $scode = input('scode/s');
                    if (!$list) {
                        alert('请选择要复制的内容！','back');
                    }
                    if (!$scode) {
                        alert('请选择目标栏目！','back');
                    }
                    if ($this->model->copyContent($list, $scode)) {
                        $this->success('复制内容成功！');
                    } else {
                        alert('复制内容失败！','back');
                    }
                    break;
                case 'move':
					$list = input('list/a');
                    $scode = input('scode/s');
                    if (! $list) {
                        alert('请选择要移动的内容！','back');
                    }
                    if (! $scode) {
                        alert('请选择目标栏目！','back');
                    }
					foreach ($list as $key => $value) {

                       // $this->model->modSlide($value, $strongdata);
						$this->model->modContent($value, array('scode'=>$scode));
                    }

					 $this->success('移动内容成功！');
				
                    /*if ($this->model->modContent($list, array('scode'=>$scode))) {

                        $this->success('移动内容成功！');
                    } else {
                        alert('移动内容失败！','back');
                    }*/
                    break;
            }
        }
        $id = input('id');
        if (!$id) {
            $this->error('传递的参数值错误！');
        }
		$this->assign('UrlParam', $UrlParam);
        // 单独修改状态
        if (($field = input('field')) && ! is_null($value = input('value'))) {
			$info[$field]=$value;
			$info['update_user']= session('username');
            if ($this->model->modContent($id,$info)) {
				location(- 1);
            } else {
                alert('修改失败！','back');
            }
        }
        // 修改操作
        if($this->request->isPost()){
            // 获取数据
            $scode = $UrlParam['scode'];
			//$mcode = $UrlParam['mcode'];
            $subscode = isset($UrlParam['subscode'])?$UrlParam['subscode']:'';
			$rund1 = isset($UrlParam['rund1'])?$UrlParam['rund1']:0;
			$rund2 = isset($UrlParam['rund2'])?$UrlParam['rund2']:0;
			$rund3 = isset($UrlParam['rund3'])?$UrlParam['rund3']:0;
            $title = $UrlParam['title'];
            $titlecolor = $UrlParam['titlecolor'];
            $subtitle = $UrlParam['subtitle'];
            $filename = $UrlParam['filename'];
            $author = $UrlParam['author'];
            $source = $UrlParam['source'];
            $outlink = $UrlParam['outlink'];
            $date =$UrlParam['date'];
            $ico = !empty($UrlParam['ico'])?$UrlParam['ico']:'';
            $pics = !empty($UrlParam['pics'])?$UrlParam['pics']:'';
            $content = $UrlParam['content'];
            $tags = str_replace('，', ',', $UrlParam['tags']);
            $enclosure = $UrlParam['enclosure'];
            $keywords = $UrlParam['keywords'];
            $description = $UrlParam['description'];
            $status = intval($UrlParam['status']);
			$istop = !empty($UrlParam['istop'])?$UrlParam['istop']:0;
            $isrecommend = !empty($UrlParam['isrecommend'])?$UrlParam['isrecommend']:0;
            $isheadline = !empty($UrlParam['isheadline'])?$UrlParam['isheadline']:0;
			$isslide = !empty($UrlParam['isslide'])?$UrlParam['isslide']:0;
            if (! $scode) {
                alert('内容分类不能为空！','back');
            }
            if (! $title) {
                alert('文章标题不能为空！','back');
            }
            if ($filename && ! preg_match('/^[a-zA-Z0-9\-]+$/', $filename)) {
                alert('内容URL名称只允许字母、数字、横线组成!','back');
            }
            // 自动提起前一百个字符为描述
            if (! $description && isset($UrlParam['content'])) {
                $description = escape_string(clear_html_blank(substr_both(strip_tags($UrlParam['content']), 0, 150)));
            }
            // 构建数据
            $data = array(
                'scode' => $scode,
                'subscode' => $subscode,
				'rund1' => $rund1,
				'rund2' => $rund2,
				'rund3' => $rund3,
                'title' => $title,
                'titlecolor' => $titlecolor,
                'subtitle' => $subtitle,
                'filename' => $filename,
                'author' => $author,
                'source' => $source,
                'outlink' => $outlink,
                'date' => $date,
                'ico' => $ico,
                'pics' => $pics,
                'content' => $content,
                'tags' => $tags,
                'enclosure' => $enclosure,
                'keywords' => $keywords,
                'description' => clear_html_blank($description),
                'status' => $status,
                'istop' => $istop,
                'isrecommend' => $isrecommend,
                'isheadline' => $isheadline,
				'isslide' => $isslide,
				'update_time' => date('Y-m-d H:i:s',time()),
                'update_user' => session('username')
            );

            // 执行添加
			$saver=$this->model->modContent($id, $data);
            if($saver!=false) {
				 // 扩展内容修改
                foreach ($UrlParam as $key => $value) {
                    if (preg_match('/^ext_[\w\-]+$/', $key)) {
                        $temp = $UrlParam[$key];
                        if (is_array($temp)) {
                            $data2[$key] = implode(',', $temp);
                        } else {
                            $data2[$key] = str_replace("\r\n", '<br>', $temp);
                        }
                    }
                }
                if (isset($data2)) {
                    if ($this->model->findContentExt($id)) {
                        $this->model->modContentExt($id, $data2);
						//echo $this->model->getlastsql();
						//die;
                    } else {
                        $data2['contentid'] = $id;
                        $this->model->addContentExt($data2);
                    }
                }

			$this->SortModel = new ContentSortModel();
			$sort_mc = $this->SortModel->getSortvalue($scode);
              $this->success('修改成功！', url('/Content/index/mcode/'.$sort_mc));
            } else {
                alert('修改失败！','back');
            }
        } else {
            // 调取修改内
            if (! $result = $this->model->getContent($id)) {
                $this->error('编辑的内容已经不存在！');
            }
            $this->assign('content', $result->toArray());
            if (! $mcode = $UrlParam['mcode']) {
                $this->error('传递的模型编码参数有误，请核对后重试！');
            }
			//文章分类下拉列表
			$this->SortModel = new ContentSortModel();

			$sort_mc = $this->SortModel->getSortvalue($mcode);

           // $sort_select = $this->SortModel->getListSelect($sort_mc);

            $sort_select = $this->SortModel->getListSelect($mcode);

			$search_select=$this->makeSortSelect($sort_select,$result->scode);

            $this->assign('search_select', $search_select);

            $this->assign('sort_select', $this->makeSortSelect($sort_select, $result->scode));

            $this->assign('subsort_select', $this->makeSortSelect($sort_select,$result->subscode));

            // 模型名称
			$ModelM=new ModelMModel();
            $this->assign('model_name', $ModelM->getName($mcode));
			$this->assign('extfield', $this->modelExt->getModelField($mcode));
			return $this->fetch("contentmod");
        }
    }
}